#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#include <arpa/inet.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

void *send_masige(void *arg)
{
    int new_socket = *(int *)arg;
    while (1)
    {
        char buf[1024] = {0};
        scanf("%s", buf);
        int send = write(new_socket, buf, 1024);
        if (send < 0)
        {
            perror("send error");
            exit(0);
        }
        else if (send == 0)
        {
            printf("客户端断开连接\n");
            break;
        }
    }
}

int main(int argc, char const *argv[])
{
    // 1. 创建socket
    int server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1)
    {
        perror("socket error");
        exit(-1);
    }

    // 2. 绑定
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(8080);
    server_addr.sin_addr.s_addr = inet_addr("172.27.208.36");
    int bind_flag = bind(server_socket, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (bind_flag < 0)
    {
        perror("bind error");
        exit(-1);
    }
    else
    printf("bind success\n");

    // 3. 监听
    int listen_flag = listen(server_socket, 5);
    if (listen_flag < 0)
    {
        perror("listen error");
        exit(-1);
    }
    else
        printf("listen success\n");

    // 4. 接受
    struct sockaddr_in client_addr;
    int len = sizeof(client_addr);
    
    printf("等待客户端连接...\n");
    int new_socket = accept(server_socket, (struct sockaddr *)&client_addr, &len);
    if (new_socket < 0)
    {
        perror("accept error");
        exit(-1);
    }
    else
        printf("客户端 %d 已连接\n", new_socket);

    // 获取客户端IP地址
    int port = ntohs(client_addr.sin_port);
    char *ip = inet_ntoa(client_addr.sin_addr);
    printf("端口：%d\n", port);
    printf("IP：%s\n", ip);

    // 5. 通信
    pthread_t tid;
    pthread_create(&tid, NULL, send_masige, &new_socket);

    while (1)
    {
        char buf[1024] = {0};
        int recv = read(new_socket, buf, sizeof(buf));
        if (recv < 0)
        {
            perror("recv error");
            exit(-1);
        }
        else if (recv == 0)
        {
            printf("客户端断开连接\n");
            break;
        }
        else
        {
            printf("%s\n",buf);
        }
    }

    return 0;
}
